<!--suppress JSMethodCanBeStatic -->
<template>
  <div class="index">
    <PhotoGrid v-model="collectionsPhotosList" :hasMore="hasMore"></PhotoGrid>
    <PhotoPreviewer></PhotoPreviewer>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

import request from '@/libs/request'
import PhotoGrid from '@/components/PhotoGrid/PhotoGrid.vue'
import PhotoPreviewer from '@/components/PhotoPreviewer.vue'

const debounce = require('lodash.debounce')

@Component({
  components: {
    PhotoGrid,
    PhotoPreviewer
  }
})
export default class Index extends Vue {
  hasMore: boolean = true
  page: number = 1
  per_page: number = 24
  photos: {
    [key: string]: any
  } = {}

  collectionsPhotosList: any[] = []

  async created(): Promise<void> {
    await this.getCollectionsPhotosList()
    this.bindScroll()
  }

  async getCollectionsPhotosList() {
    if (this.hasMore) {
      this.photos = await request.listCollectionsPhotos({
        page: this.page,
        per_page: this.per_page
      })

      if (this.photos.data.length > 0) {
        this.page++
      } else {
        this.hasMore = false
      }

      this.updateCollectionsPhotosList()
    }
  }

  updateCollectionsPhotosList() {
    if (this.photos.data) {
      this.collectionsPhotosList.push(...this.photos.data)
    }
  }

  get height() {
    return document.documentElement.clientHeight
  }

  scrollHeight() {
    return document.body.scrollHeight == 0
      ? document.documentElement.scrollHeight
      : document.body.scrollHeight
  }

  scrollTop() {
    return document.body.scrollTop == 0
      ? document.documentElement.scrollTop
      : document.body.scrollTop
  }

  offset() {
    return this.scrollHeight() - this.height - this.scrollTop()
  }

  bindScroll(): void {
    window.addEventListener(
      'scroll',
      debounce(async () => {
        if (this.offset() > 100) return false

        await this.getCollectionsPhotosList()
      }, 500)
    )
  }
}
</script>

<style lang="scss" scoped>
.index {
  position: relative;
}
</style>
